package com.hsyt.pms.controller.system;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hsyt.pfc.support.rpc.PageResult;
import com.hsyt.pfc.support.util.EnumToDataUtil;
import com.hsyt.pfc.support.util.LoggerUtil;
import com.hsyt.pms.api.common.PltAuth;
import com.hsyt.pms.api.common.PltLog;
import com.hsyt.pms.api.common.ResultMessage;
import com.hsyt.pms.api.dto.system.SysCityDto;
import com.hsyt.pms.api.enums.AbleStatus;
import com.hsyt.pms.api.enums.CityType;
import com.hsyt.pms.api.vo.system.SysCityVo;
import com.hsyt.pms.controller.base.BaseController;
import com.hsyt.pms.sys.dubbo.SysCityService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: SysCityController
 * @Description: 系统城市控制层
 * @author: wangze@hsyuntai.com
 * @date: 2019/1/29 18:19
 */
@RestController
@RequestMapping("/pms/system/city")
public class SysCityController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysCityController.class);

    @Reference(group = "pmsSystem", registry = "pms", version = "0.0.1")
    private SysCityService sysCityService;

    @RequestMapping(value = "/page")
    @PltAuth(auth = "ROLE_CITY_MG")
    public ModelAndView page(ModelMap model) {
        SysCityDto sysCityDto = new SysCityDto();
        sysCityDto.setStatus(AbleStatus.ENABLED.getCode());
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(AbleStatus.class);
        model.put("statusComboData", statusComboData);
        String cityTypeComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(CityType.class);
        model.put("cityTypeComboData", cityTypeComboData);
        return new ModelAndView("city/pageCity", model);
    }

    @RequestMapping(value = "/findPageData")
    @PltAuth(auth = "ROLE_CITY_MG")
    public @ResponseBody
    PageResult findPageData(@RequestBody SysCityDto dto) {
        PageResult<SysCityVo> pageResult = new PageResult<SysCityVo>();
        try {
            pageResult = sysCityService.searchPageDataByDto(dto);
        } catch (Exception e) {
            pageResult.setResult(false);
            String message = MessageFormat.format("SysCityController.searchPageData error: {0}", e.getMessage());
            pageResult.setMessage(message);
            LoggerUtil.error(LOGGER, message);
        }
        return pageResult;
    }

    @RequestMapping(value = "/toEditForm")
    @PltAuth(auth = "ROLE_CITY_MG_ADD,ROLE_CITY_MG_MODIFY")
    public ModelAndView toEditForm(ModelMap model, @RequestParam("formType") String formType) {
        model.put("formType", formType);
        return new ModelAndView("city/formCity");
    }

    @PltLog(log = "保存城市")
    @RequestMapping(value = "/save")
    @PltAuth(auth = "ROLE_CITY_MG_ADD,ROLE_CITY_MG_MODIFY")
    public @ResponseBody
    ResultMessage save(@RequestBody SysCityDto dto, String formType, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        try {
            if (dto.getId() == null) {
                dto.setStatus(AbleStatus.ENABLED.getCode());
                this.sysCityService.insertSysCity(dto);
            } else {
                this.sysCityService.updateByPrimaryKey(dto);
            }
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "SysWhiteController-save error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/openEditSysCityPage")
    public ModelAndView openEditSysCityPage(ModelMap model, String type) {
        model.put("type", type);
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(AbleStatus.class);
        model.put("statusComboData", statusComboData);
        String cityTypeComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(CityType.class);
        model.put("cityTypeComboData", cityTypeComboData);
        return new ModelAndView("city/win/editSysCity", model);
    }

    @RequestMapping(value = "/doUndo")
    @PltAuth(auth ="ROLE_CITY_MG_DELETE")
    public @ResponseBody
    ResultMessage doUndoSysParam(@RequestBody SysCityDto dto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        try {
            this.sysCityService.updateByPrimaryKey(dto);
        } catch (Exception e) {
            result.change(false, "操作失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "SysParam-doUndoSysCity error:{0} param:{1}", e.getMessage(), dto);
        }
        return result;
    }

    @RequestMapping(value = "/addSysCity")
    public @ResponseBody
    ResultMessage addSysCity(@RequestBody SysCityDto sysCityDto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "新增成功");
        try {
            //常规校验
            ResultMessage resultCheck = infoCheck(sysCityDto);
            if (!resultCheck.isResult()) {
                return resultCheck;
            }
            //数据处理
            if (StringUtils.isBlank(sysCityDto.getCityCode())) {
                result.change(false, "城市编码不可为空");
                return result;
            }
            SysCityVo.makeCityParentCode(sysCityDto);
            this.sysCityService.insertSysCity(sysCityDto);
        } catch (Exception e) {
            result.change(false, "新增失败" + e.getMessage());

        }
        return result;
    }

    @RequestMapping(value = "/editSysCity")
    public @ResponseBody
    ResultMessage editSysCity(@RequestBody SysCityDto sysCityDto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "更新成功");
        try {
            SysCityVo.makeCityParentCode(sysCityDto);
            this.sysCityService.updateByPrimaryKey(sysCityDto);
        } catch (Exception e) {
            result.change(false, "更新失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "dict-editSysCity error: {0}", e.getMessage());
        }
        return result;
    }

    public ResultMessage infoCheck(@RequestBody SysCityDto sysCityDto) {
        ResultMessage resultMessage = new ResultMessage(true, "检查成功");
        try {
            if (sysCityDto == null) {
                resultMessage.change(false, "对象为空！");
                return resultMessage;
            }
            if (StringUtils.isBlank(sysCityDto.getCityName())) {
                resultMessage.change(false, "城市名称为空！");
                return resultMessage;
            }
            if (StringUtils.isBlank(sysCityDto.getCityCode())) {
                resultMessage.change(false, "城市编码为空！");
                return resultMessage;
            }
            return resultMessage;
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, e.getMessage());
            return resultMessage;
        }
    }

    @RequestMapping(value = "/getCity")
    public @ResponseBody
    ResultMessage getCity(@RequestBody SysCityDto sysCityDto) {
        ResultMessage result = new ResultMessage(true, "获取城市列表成功");
        try {
            sysCityDto.setStatus(AbleStatus.ENABLED.getCode());
            String countyComboData = EnumToDataUtil.getComboData(this.sysCityService.listCity(sysCityDto), "cityCode", "cityName", null);
            result.setContent(countyComboData);
        } catch (Exception e) {
            result.change(false, "获取城市列表失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "city-getCity error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/getCityAndCounty")
    public @ResponseBody
    ResultMessage getCityAndCounty(@RequestBody SysCityDto sysCityDto) {
        ResultMessage result = new ResultMessage(true, "获取城市列表成功");
        Map content = new HashMap<String, String>(4);
        try {
            sysCityDto.setStatus(AbleStatus.ENABLED.getCode());
            String cityCode = sysCityDto.getCityCode();
            String provinceValue = StringUtils.substring(cityCode, 0, 2);
            String cityValue = StringUtils.substring(cityCode, 0, 4);
            if (StringUtils.length(provinceValue) == 2) {
                sysCityDto.setParentCityCode(provinceValue);
                sysCityDto.setCityCode(null);
                sysCityDto.setCityType(CityType.CITY.getCode());
                String cityComboData = EnumToDataUtil.getComboData(this.sysCityService.listCity(sysCityDto), "cityCode", "cityName", null);
                content.put("cityComboData", cityComboData);
            }
            if (StringUtils.length(cityValue) == 4) {
                sysCityDto.setParentCityCode(cityValue);
                sysCityDto.setCityCode(null);
                sysCityDto.setCityType(CityType.COUNTY.getCode());
                String countyComboData = EnumToDataUtil.getComboData(this.sysCityService.listCity(sysCityDto), "cityCode", "cityName",
                        null);
                content.put("countyComboData", countyComboData);
            }
            content.put("cityValue", cityValue == null ? "" : cityValue);
            content.put("countyValue", cityCode == null ? "" : cityCode);
            result.setContent(content);
        } catch (Exception e) {
            result.change(false, "获取城市列表失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "city-getCity error: {0}", e.getMessage());
        }
        return result;
    }
}
